package com.wyy.service.impl;

import com.wyy.mapper.ArticleMapper;
import com.wyy.mapper.CommentMapper;
import com.wyy.mapper.UserMapper;
import com.wyy.pojo.Comments;
import com.wyy.pojo.model.CommentModel;
import com.wyy.pojo.model.CommentQuery;
import com.wyy.pojo.model.UserToken;
import com.wyy.service.CommentService;
import com.wyy.util.MyUtil;
import com.wyy.util.TokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: gytcb
 * @author: 吴磊
 * @create: 2021-06-03 20:21
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TokenUtils tokenUtils;


    @Autowired
    private UserMapper userMapper;

    private MyUtil myUtil = new MyUtil();

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Map<String, Object> insertComment(Comments comments) {
        String commentId = myUtil.getUUID();
        String commentDate = myUtil.getCurrentDetailedTime();
        comments.setCommentId(commentId);
        comments.setCommentDate(commentDate);
        String userId = tokenUtils.parseTokenToUserToken().getUserId();
        comments.setUserId(userId);
        //插入评论
        commentMapper.insertComment(comments);
        //添加文章评论数
        articleMapper.incrArticleCommentCount(comments.getArticleId());
        //获取最新的文章评论数
        Integer articleCommentCount = commentMapper.getArticleCommentCount(comments.getArticleId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("articleCommentCount", articleCommentCount == null ? 0 : articleCommentCount);
        return map;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Map<String, Object> deleteComment(Comments comments) {
        String commentId = comments.getCommentId();
        String articleId = commentMapper.getArticleIdByCommentId(commentId);
        commentMapper.deleteCommentById(commentId);
        articleMapper.decrArticleCommentCount(articleId);
        Integer articleCommentCount = commentMapper.getArticleCommentCount(comments.getArticleId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("articleCommentCount", articleCommentCount == null ? 0 : articleCommentCount);
        return map;
    }

    /**
     * {
     * "articleId": "这个参数只是在查看文章评论的时候有用，一旦userID不为空，这个参数要不要都无所谓",
     * "userId": "如果这个参数为空就查询文章的评论，如果不为空：1、别人查看评论2、自己查看评论",
     * "curPage": 1
     * }
     *
     * @param commentQuery
     * @return
     */
    @Override
    public Map<String, Object> getCommentByArticleIdOrUserId(CommentQuery commentQuery) {

        /**
         * 获取评论分为3总情况
         * 1、获取文章的评论
         * 2、根据文章评论获取用户的全部评论
         * 2.1、用户匿名评论（不可查看用户主页）
         * 2.2、用户不匿名评论
         * 3、用户查看自己的全部评论
         */

        HashMap<String, Object> map = new HashMap<>();
        String userId = commentQuery.getUserId();
        String articleId = commentQuery.getArticleId();
        List<Comments> comments;
        List<CommentModel> commentModels = null;
        int curPage = commentQuery.getCurPage();
        if (curPage <= 0) {
            curPage = 1;
        }
        //全部的条数
        int totalCount = 0;
        //全部的页数
        int totalPage = 0;

        //1、先判断是获取用户的评论还是获取文章的评论
        if (StringUtils.isEmpty(userId)) {
            //获取文章评论
            //1、获取评论总数
            Integer count = commentMapper.getArticleCommentCount(articleId);
            totalCount = count == null ? 0 : count;
            totalPage = (totalCount + 50 - 1) / 50;
            if (totalPage <= 0) {
                map.put("totalCount", 0);
                map.put("totalPage", 0);
                map.put("comments", new ArrayList<>());
                return map;
            }
            if (curPage > totalPage) {
                curPage = totalPage;
            }
            //2、查出当页的评论
            comments = commentMapper.getCommentByArticleId(articleId, (curPage - 1) * 50);
            //最后一步：处理评论（是否匿名）
            commentModels = comments.stream().map(comment -> {
                CommentModel commentModel = new CommentModel();
                BeanUtils.copyProperties(comment, commentModel);
                if ("1".equals("" + comment.getCommentsStatus())) {
                    //不匿名
                    UserToken user = userMapper.getUserById(comment.getUserId());
                    commentModel.setUserToken(user);
                } else {
                    //匿名
                    UserToken userToken = new UserToken();
                    userToken.setUserId(comment.getUserId());
                    userToken.setUserNickname("匿名");
                    userToken.setUserProfilePhoto("http://www.6our.com/Public/face/f_noface.png");
                    userToken.setUserRegistrationTime("");
                    commentModel.setUserToken(userToken);
                }
                return commentModel;
            }).collect(Collectors.toList());
            //返回结果
            map.put("totalCount", totalCount);
            map.put("totalPage", totalPage);
            map.put("comments", commentModels);
            return map;
        } else {
            //获取用户全部的评论
            /**
             * 1、通过评论查看用户主页
             * 2、自己查看自己主页和自己通过评论查看情况一样
             */

            boolean isOwner = true;
            String s1 = tokenUtils.parseTokenToken();
            if (StringUtils.isEmpty(s1)) {
                //说明没有登录
                isOwner = false;
            } else {
                //登录了，接下来判断是不是自己的评论
                UserToken loginUser = tokenUtils.getInfoFromToken(s1);
                String loginUserId = loginUser.getUserId();
                if (loginUserId.equals(userId)) {
                    //说明是自己的评论
                    totalCount = commentMapper.getUserCommentCount(userId);
                    totalPage = (totalCount + 50 - 1) / 50;
                    if (totalPage <= 0) {
                        map.put("totalCount", 0);
                        map.put("totalPage", 0);
                        map.put("comments", new ArrayList<>());
                        return map;
                    }
                    if (curPage > totalPage) {
                        curPage = totalPage;
                    }
                    comments = commentMapper.getUserComments(userId, (curPage - 1) * 50);
                    commentModels = comments.stream().map(comment -> {
                        CommentModel commentModel = new CommentModel();
                        BeanUtils.copyProperties(comment, commentModel);
                        commentModel.setUserToken(loginUser);
                        return commentModel;
                    }).collect(Collectors.toList());

                } else {
                    //说明是别人查看评论
                    isOwner = false;
                }

            }
            if (!isOwner) {
                totalCount = commentMapper.getUserCommentCountNotNnonymous(userId);
                totalPage = (totalCount + 50 - 1) / 50;
                if (totalPage <= 0) {
                    map.put("totalCount", 0);
                    map.put("totalPage", 0);
                    map.put("comments", new ArrayList<>());
                    return map;
                }
                if (curPage > totalPage) {
                    curPage = totalPage;
                }
                comments = commentMapper.getUserCommentsNotNnonymous(userId, (curPage - 1) * 50);
                UserToken userById = userMapper.getUserById(userId);
                commentModels = comments.stream().map(comment -> {
                    CommentModel commentModel = new CommentModel();
                    BeanUtils.copyProperties(comment, commentModel);
                    commentModel.setUserToken(userById);
                    return commentModel;
                }).collect(Collectors.toList());

            }
        }

        //返回结果
        map.put("totalCount", totalCount);
        map.put("totalPage", totalPage);
        map.put("comments", commentModels);
        return map;
    }
}
